<%--
  Created by IntelliJ IDEA.
  User: 47474
  Date: 2021/8/7
  Time: 11:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
  pageContext.setAttribute("APP_PATH",request.getContextPath());
%>
<script type="text/javascript" src="${APP_PATH}/static/js/jquery-3.6.0.js"></script>
<link rel="stylesheet" type="text/css" href="${APP_PATH}/static/bootstrap-3.4.1-dist/css/bootstrap.min.css"/>
<script type="text/javascript" src="${APP_PATH}/static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>

<html>
<head>
  <title>User List</title>
</head>
<body>

<%--添加用户的弹窗--%>
<div class="modal fade" id="addUserModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">添加用户</h4>
      </div>
      <div class="modal-body">
<%--        表单--%>
        <form class="form-horizontal" id="addForm">
          <div class="form-group">
            <label for="userName_add_input" class="col-sm-2 control-label">昵称</label>
            <div class="col-sm-10">
              <input name="userName" type="text" class="form-control" id="userName_add_input" placeholder="昵称">
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group">
            <label for="password_add_input" class="col-sm-2 control-label">密码</label>
            <div class="col-sm-10">
              <input name="userPassword" type="text" class="form-control" id="password_add_input" placeholder="密码">
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group">
            <label for="password_add_input" class="col-sm-2 control-label">性别</label>
            <div class="col-sm-10">
<%--              性别--%>
              <label class="radio-inline">
                <input type="radio" name="gender" id="gender1" value="男"> 男
              </label>
              <label class="radio-inline">
                <input type="radio" name="gender" id="gender2" value="女"> 女
              </label>
            </div>
          </div>
          <div class="form-group">
            <label for="age_add_input" class="col-sm-2 control-label">年龄</label>
            <div class="col-sm-10">
              <input name="age" type="text" class="form-control" id="age_add_input" placeholder="年龄">
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group">
            <label for="email_add_input" class="col-sm-2 control-label">邮箱</label>
            <div class="col-sm-10">
              <input name="email" type="email" class="form-control" id="email_add_input" placeholder="邮箱">
              <span class="help-block"></span>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="user_save_btn">确定</button>
      </div>
    </div>
  </div>
</div>


<%--修改用户的弹窗--%>
<div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myEditModalLabel">修改用户</h4>
      </div>
      <div class="modal-body">
        <%--        表单--%>
        <form class="form-horizontal" id="addForm">
          <div class="form-group">
            <label for="userName_add_input" class="col-sm-2 control-label">昵称</label>
            <div class="col-sm-10">
              <p class="form-control-static" id="userName_edit_static"></p>
            </div>
          </div>
          <div class="form-group">
            <label for="password_add_input" class="col-sm-2 control-label">密码</label>
            <div class="col-sm-10">
              <input name="userPassword" type="text" class="form-control" id="password_edit_input" placeholder="密码">
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group">
            <label for="password_add_input" class="col-sm-2 control-label">性别</label>
            <div class="col-sm-10">
              <%--              性别--%>
              <label class="radio-inline">
                <input type="radio" name="gender" id="editgender1" value="男"> 男
              </label>
              <label class="radio-inline">
                <input type="radio" name="gender" id="editgender2" value="女"> 女
              </label>
            </div>
          </div>
          <div class="form-group">
            <label for="age_add_input" class="col-sm-2 control-label">年龄</label>
            <div class="col-sm-10">
              <input name="age" type="text" class="form-control" id="age_edit_input" placeholder="年龄">
              <span class="help-block"></span>
            </div>
          </div>
          <div class="form-group">
            <label for="email_add_input" class="col-sm-2 control-label">邮箱</label>
            <div class="col-sm-10">
              <input name="email" type="email" class="form-control" id="email_edit_input" placeholder="邮箱">
              <span class="help-block"></span>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="user_edit_btn">确定</button>
      </div>
    </div>
  </div>
</div>


<div class="container">
  <div class="row">
    <div class="col-md-12">
      <h2>用户列表管理</h2>
    </div>
  </div>
  <div class="row">
    <div class="col-md-4 col-md-offset-8" style="margin-bottom: 20px">
      <button class="btn btn-primary" data-toggle="modal" data-target="#addUserModal" id="addUserBtn">添加</button>
      <button class="btn btn-danger" id="deleteAllUserBtn">删除</button>
    </div>
  </div>
  <div class="row">
    <div class="col-md-12">
      <table class="table table-hover" id="user_table">
        <thead>
        <tr>
          <th>
            <input type="checkbox" id="check_all">
          </th>
          <th>#</th>
          <th>昵称</th>
          <th>密码</th>
          <th>性别</th>
          <th>年龄</th>
          <th>邮箱</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody></tbody>

      </table>
    </div>
  </div>

  <%--    分页信息--%>
  <div class="row">
    <%--        分页文字信息--%>
    <div class="col-md-4 col-xs-6" id="page_info_area"></div>
    <%--        分页条信息--%>
    <div class="col-md-8 col-xs-6" id="page_nav_area">
    </div>
  </div>
</div>

<script type="text/javascript">

  //总记录数
  var totalRecords;
  //当前页
  var currentPage;


  $(function (){
    //去首页
    to_page(1);
  })
  function to_page(pn){
    $.ajax({
      url: "${APP_PATH}/user/list",
      data: "pn="+pn,
      type: "GET",
      success:function (result){
        //console.log(result);成功
        //解析用户数据
        build_user_table(result);
        //解析分页数据
        build_page_info(result);
        build_page_nav(result)
      }
    })
  }

  function build_user_table(result){
    //清空table表格
    $("#user_table tbody").empty();

      var user = result.extend.pageInfo.list;
      $.each(user,function (index,item){
        var checkBox = $("<td><input type='checkbox' class='check_item'/></td>")
        var userIdtd = $("<td></td>").append(item.userId);
        var userNametd = $("<td></td>").append(item.userName);
        var userPasswordtd = $("<td></td>").append(item.userPassword);
        var gendertd = $("<td></td>").append(item.gender);
        var agetd = $("<td></td>").append(item.age);
        var emailtd = $("<td></td>").append(item.email);
        var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
                        .append($("<span></span>").addClass("glyphicon glyphicon-pencil"))

        //为编辑按钮添加一个自定义的属性，来表示当前用户的id
        editBtn.attr("edit_id",item.userId);

        var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm del_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash"))
        //当前删除的id
        delBtn.attr("del_id",item.userId);

        var btntd = $("<td></td>").append(editBtn).append(" ").append(delBtn);

        $("<tr></tr>").append(checkBox).append(userIdtd).append(userNametd).append(userPasswordtd).append(gendertd).append(agetd).append(emailtd)
        .append(btntd).appendTo("#user_table tbody");
      })
  }

  //分页信息数据
  function build_page_info(result){
    $("#page_info_area").empty();
        $("#page_info_area").append("当前第"+result.extend.pageInfo.pageNum+"页，共"+result.extend.pageInfo.pages+"页，共有"+result.extend.pageInfo.total+"条记录")
    totalRecords = result.extend.pageInfo.total;
        currentPage = result.extend.pageInfo.pageNum;
  }

  //解析分页条
  function build_page_nav(result){
    $("#page_nav_area").empty();
        var ul = $("<ul></ul>").addClass("pagination");
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));
        if(result.extend.pageInfo.hasPreviousPage == false){
          firstPageLi.addClass("disabled");
          prePageLi.addClass("disabled");
        }else {
          //上一页
          firstPageLi.click(function (){
            to_page(1);
          })
          prePageLi.click(function (){
            to_page(result.extend.pageInfo.pageNum-1);
          })
        }

        ul.append(firstPageLi).append(prePageLi);
        $.each(result.extend.pageInfo.navigatepageNums,function (index,item){
              var numLi = $("<li></li>").append($("<a></a>").append(item));
              if(result.extend.pageInfo.pageNum == item){
                numLi.addClass("active");
              }
              numLi.click(function (){
                to_page(item);
              })

              ul.append(numLi);
        });

        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"));
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
        if(result.extend.pageInfo.hasNextPage == false){
           nextPageLi.addClass("disabled");
           lastPageLi.addClass("disabled");
        }else {
          nextPageLi.click(function (){
            to_page(result.extend.pageInfo.pageNum+1);
          })
          lastPageLi.click(function (){
            to_page(result.extend.pageInfo.pages);
          })
        }
        ul.append(nextPageLi).append(lastPageLi);

        var navEle = $("<nav></nav>").append(ul);
        navEle.appendTo("#page_nav_area");
  }

  //模态框关闭后重置表单 数据+样式
  $("#addUserModal").on("hide.bs.modal",function (){
    $("#addUserModal form")[0].reset();//清空表单内容
    //清空样式
    $("#addUserModal form").find("*").removeClass("has-error has-success")
    $("#addUserModal form").find(".help-block").text("")
  })

  //验证表单
  function validate_add_form(){
    var userName = $("#userName_add_input").val();
    var regName = /(^[a-zA-Z0-9_-]{3,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
    if(!regName.test(userName)){
      show_validate_msg("#userName_add_input","error","用户名不符合要求")
        return false;
    }else {
      show_validate_msg("#userName_add_input","success","")
    }

    var userPassword = $("#password_add_input").val();
    var regPassword = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
    if(!regPassword.test(userPassword)){
      show_validate_msg("#password_add_input","error","密码格式不符合要求")
      return false;
    }else {
      show_validate_msg("#password_add_input","success","")
    }

    var age = $("#age_add_input").val();
    if(age<=0||age>=130){
      show_validate_msg("#age_add_input","error","年龄有误")
      return false;
    }else {
      show_validate_msg("#age_add_input","success","")
    }

    var email = $("#email_add_input").val();
    var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
    if(!regEmail.test(email)){
      show_validate_msg("#email_add_input","error","邮箱格式不正确")
      return false;
    }else {
      show_validate_msg("#email_add_input","success","")
    }

    return true;
  }

  //表单验证不通过的提示
  function show_validate_msg(ele,status,msg){
    $(ele).parent().removeClass("has-success has-error");
    $(ele).next("span").text("");
    if("success" == status){
        $(ele).parent().addClass("has-success");
        $(ele).next("span").text(msg)
    }else if("error"==status){
        $(ele).parent().addClass("has-error");
        $(ele).next("span").text(msg)
    }
  }

  //判断昵称是否重复
  $("#userName_add_input").change(function (){
    //用户名是否可用‘
    var userName = this.value;
    $.ajax({
      url: "${APP_PATH}/user/checkuser",
      data: "userName="+userName,
      type: "POST",
      success: function (result){
        if(result.code == 100){
          show_validate_msg("#userName_add_input","success","用户名可用")
          $("#user_save_btn").attr("ajax_va","success")
        }else {
          show_validate_msg("#userName_add_input","error",result.extend.va_msg);
          $("#user_save_btn").attr("ajax_va","error")
        }
      }
    })
  })

  //提交表单数据
  $("#user_save_btn").click(function (){
    //console.log($("#addUserModal form").serialize())

    // 前端校验
    if(!validate_add_form()){
      return false;
    }
    //判断之前的ajax用户名校验是否成功，不 成功：
    if($(this).attr("ajax_va")=="error"){
      return false;
    }

    //提交表单到数据库
    $.ajax({
      url: "${APP_PATH}/user/usersave",
      type: "POST",
      data: $("#addUserModal form").serialize(),
      success: function (result){
        // alert(result.msg);

        if(result.code == 100){
          //关闭模态框
          $("#addUserModal").modal('hide');
          //来到最后一页显示
          //显示最后一页数据
          to_page(totalRecords);
        }else {
          //显示失败信息
          //console.log(result)
          //有哪个错误的信息，就显示哪个字段的
          if(undefined != result.extend.errorFields.email){
            //显示邮箱的错误信息
            show_validate_msg("#email_add_input","error",result.extend.errorFields.email)
          }
          if(undefined != result.extend.errorFields.userName){
            //显示用户名的错误信息
            show_validate_msg("#userName_add_input","error",result.extend.errorFields.userName)
          }
        }
      }
    });
  })

  //创建按钮的时候绑定事件
  $(document).on("click",".edit_btn",function (){
    // alert("edit");
    //显示用户的数据传给更新按钮
    $("#user_edit_btn").attr("edit_id",$(this).attr("edit_id"));
    getUser($(this).attr("edit_id"));
    //把用户的id
    $("#editUserModal").modal({

    })
  })

  function getUser(id){
    $.ajax({
      url: "${APP_PATH}/user/usersave/"+id,
      type: "GET",
      success: function (result){
        // console.log(result);
        var userData = result.extend.user;
        //渲染数据
        $("#userName_edit_static").text(userData.userName);
        $("#password_edit_input").val(userData.userPassword);
        $("#editUserModal input[name=gender]").val([userData.gender]);
        $("#age_edit_input").val(userData.age);
        $("#email_edit_input").val(userData.email);
      }
    })
  }

  //更新按钮 绑定事件
  $("#user_edit_btn").click(function (){
    //更新数据提交之前 要进行表单验证
    //密码验证
    var userPassword = $("#password_edit_input").val();
    var regPassword = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
    if(!regPassword.test(userPassword)){
      show_validate_msg("#password_edit_input","error","密码格式不符合要求")
      return false;
    }else {
      show_validate_msg("#password_edit_input","success","")
    }
    //年龄验证
    var age = $("#age_edit_input").val();
    if(age<=0||age>=130){
      show_validate_msg("#age_edit_input","error","年龄有误")
      return false;
    }else {
      show_validate_msg("#age_edit_input","success","")
    }
    //邮箱
    var email = $("#email_edit_input").val();
    var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
    if(!regEmail.test(email)){
      show_validate_msg("#email_edit_input","error","邮箱格式不正确")
      return false;
    }else {
      show_validate_msg("#email_edit_input","success","")
    }

    //发送ajax请求
    $.ajax({
      url: "${APP_PATH}/user/usersave/"+$(this).attr("edit_id"),
      type: "PUT",
      data: $("#editUserModal form").serialize(),
      success: function (result){
        $("#editUserModal").modal("hide");
        to_page(currentPage);
      }
    })
  })


  //删除功能
  //单个删除
  $(document).on("click",".del_btn",function (){
    var userName = $(this).parents("tr").find("td:eq(1)").text();
    var userId = $(this).attr("del_id");
    if(confirm("确认删除【"+userName+"】吗？")){
      //确认删除
      $.ajax({
        url: "${APP_PATH}/user/userdel/"+userId,
        type: "DELETE",
        success: function (result){
          alert(result.msg);
          to_page(currentPage);
        }
      })
    }
  })


  //全选  全不选
  $("#check_all").click(function (){
    // attr 获取checked是undefined
    //这些dom的原生属性 都用prop来获取
    // alert($(this).attr("checked"))
    //alert($(this).prop("checked"))  //被选true
    // check_item 的值为$(this).prop("checked")
    $(".check_item").prop("checked",$(this).prop("checked"))
  });

  // check_item  后来动态添加的用 document
  $(document).on("click",".check_item",function (){
    //判断当前选中的元素是否是8个
    var flag = $(".check_item:checked").length==$(".check_item").length;
    $("#check_all").prop("checked",flag)
  });



  // 批量删除按钮
  $("#deleteAllUserBtn").click(function (){
    //$(".check_item:checked") 每一个被选中的多选框
    var userNames = "";
    var del_idstr = "";
    $.each($(".check_item:checked"),function (){
      userNames += $(this).parents("tr").find("td:eq(2)").text()+",";
      del_idstr += $(this).parents("tr").find("td:eq(1)").text()+"-";
    });
    //取出都好
    userNames = userNames.substring(0,userNames.length-1);
    del_idstr = del_idstr.substring(0,del_idstr.length-1);
    if(confirm("确认删除【"+userNames+"】吗？")){
      //ajax删除
      $.ajax({
        url: "${APP_PATH}/user/userdel/"+del_idstr,
        type: "DELETE",
        success: function (result){
          alert(result.msg);
          to_page(currentPage);
        }
      })
    }

  });




</script>

</body>
</html>
